package com.yzx.lifeassistants.model.impl;

import java.util.List;
import java.util.Properties;

import android.content.Context;

import com.yzx.lifeassistants.bean.MyBook;
import com.yzx.lifeassistants.model.ILoginLibrary;
import com.yzx.lifeassistants.model.analysis.LoginLibraryAnalysis;
import com.yzx.lifeassistants.model.callback.ILoginLibraryCB;
import com.yzx.lifeassistants.utils.HttpClientUtil;
import com.yzx.lifeassistants.utils.IHttpCallBack;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.PropertyUtil;

/**
 * @Description: 图书馆登录
 * @author: yzx
 * @time: 2016-3-9 下午8:25:10
 */
public class LoginLibraryImpl implements ILoginLibrary {
	public static final String TAG = "loginLibrary";
	private String url;// URL
	private ILoginLibraryCB loginCallBack;// 回调

	public LoginLibraryImpl(Context context, ILoginLibraryCB loginCallBack) {
		this.loginCallBack = loginCallBack;
		Properties properties = PropertyUtil.getProperties(context,
				"base.properties");
		url = properties.getProperty("login_library_url");
	}

	/**
	 * 
	 * @Description: 图书馆登录
	 */
	@Override
	public void loginLibrary(String username, String password) {
		HttpClientUtil.sendRequest(url + "?user=" + username + "&psw="
				+ password, null, new IHttpCallBack() {

			@Override
			public void onFinish(String response) {
				LogcatUtils.i(response);
				boolean isLoginFailed = LoginLibraryAnalysis
						.isLoginFailed(response);
				if (isLoginFailed) {// 登录失败
					LogcatUtils.e("登录图书馆失败");
					loginCallBack.loginError(ILoginLibraryCB.LOGIN_FAILED);
				} else {// 登录成功
					LogcatUtils.i("登录图书馆成功");
					boolean isMyBookNull = LoginLibraryAnalysis
							.isMyBookNull(response);
					if (isMyBookNull) {// 借阅为空
						LogcatUtils.e("我的借阅图书为空");
						loginCallBack.loginSuccess(null,
								ILoginLibraryCB.RESULR_NULL);
					} else {
						List<MyBook> myBookList = LoginLibraryAnalysis
								.getMyBooks(response);
						if (null == myBookList || 1 > myBookList.size()) {
							LogcatUtils.e("我的借阅图书为空");
							loginCallBack.loginSuccess(null,
									ILoginLibraryCB.RESULR_NULL);
						} else {
							LogcatUtils.i("查阅我的借阅图书成功");
							loginCallBack.loginSuccess(myBookList,
									ILoginLibraryCB.LOGIN_SUCCESS);
						}
					}
				}
			}

			@Override
			public void onError(Exception e) {
				LogcatUtils.e("获取数据失败");
				if (null != e.getMessage()) {
					LogcatUtils.e(e.getMessage());
				}
				loginCallBack.loginError(ILoginLibraryCB.LOGIN_ERROR);
			}
		});
	}

}
